namespace Dascoba.Umb.Controls
{
    using System;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Xml;

    using AjaxControlToolkit;

    using umbraco.cms.businesslogic.member;
    using umbraco.cms.businesslogic.property;
    using umbraco.editorControls;
    using umbraco.editorControls.simpleEditor;
    using umbraco.editorControls.textfield;
    using umbraco.editorControls.tinyMCE3;
    using umbraco.editorControls.ultimatepicker;

    public partial class ProfileEditor : UserControl
    {
        #region Properties

        private static MemberType _currentMemberType;
        private Member _currentMember;

        #endregion

        #region Methods

        /// <summary>
        /// Registers the scripts.
        /// </summary>
        private static void RegisterScripts() {}

        /// <summary>
        /// Builds the property editor.
        /// </summary>
        private void BuildPropertyEditor()
        {
            _currentMemberType = MemberType.GetByAlias(this._currentMember.ContentType.Alias);

            // Iterate through membertype tabs
            foreach (var tab in _currentMemberType.getVirtualTabs)
            {
                var tabPanel = new TabPanel {HeaderText = tab.Caption};

                this.TabContainer1.Tabs.Add(tabPanel);

                var propertyTable = new Table
                                    {
                                            BorderStyle = BorderStyle.None,
                                            BorderWidth = Unit.Pixel(0),
                                            Width = Unit.Percentage(100)
                                    };
                tabPanel.Controls.Add(propertyTable);

                // Iterate through properties on tab
                foreach (var propertyType in tab.PropertyTypes)
                {
                    // Check if property is allowed to be viewed
                    if (!_currentMemberType.ViewOnProfile(propertyType))
                        continue;

                    // Build the property GUI
                    var propertyLabel = new Label
                                        {ID = string.Format("lbl{0}", propertyType.Alias), Text = propertyType.Name};
                    var propertyEditor = GetPopulatedEditor(this._currentMember.getProperty(propertyType));

                    if (propertyEditor == null)
                        continue;

                    // Table Row
                    var propertyRow = new TableRow();
                    propertyTable.Rows.Add(propertyRow);

                    // Row Cells
                    var labelCell = new TableCell {Width = Unit.Percentage(33)};
                    var propertyCell = new TableCell {Width = Unit.Percentage(66)};
                    propertyRow.Cells.Add(labelCell);
                    propertyRow.Cells.Add(propertyCell);

                    // Add Label and Property to cells
                    labelCell.Controls.Add(propertyLabel);
                    propertyCell.Controls.Add(propertyEditor);
                }
            }
            this.TabContainer1.ActiveTabIndex = 0;
        }

        /// <summary>
        /// Gets the populated editor.
        /// </summary>
        /// <param name="property">The property.</param>
        /// <returns></returns>
        private Control GetPopulatedEditor(Property property)
        {
            if (property.PropertyType == null)
                return null;

            var dataEditorControl = property.PropertyType.DataTypeDefinition.DataType.DataEditor.Editor;
            dataEditorControl.ID = string.Format("editor{0}", property.PropertyType.Alias);

            var controlType = dataEditorControl.GetType().ToString();
            switch (controlType)
            {
                case "umbraco.editorControls.textfield.TextFieldEditor":
                case "umbraco.editorControls.textfieldmultiple.textfieldMultipleDataType":
                    {
                        ((TextFieldEditor) dataEditorControl).Text = property.Value.ToString();
                        ((TextFieldEditor) dataEditorControl).TextChanged += Editor_TextChanged;
                        if (!_currentMemberType.MemberCanEdit(property.PropertyType))
                            ((TextFieldEditor) dataEditorControl).Enabled = false;
                    }
                    break;
                case "umbraco.editorControls.numberfield":
                    {
                        ((numberField) dataEditorControl).Text = property.Value.ToString();
                        ((numberField) dataEditorControl).TextChanged += Editor_TextChanged;
                        if (!_currentMemberType.MemberCanEdit(property.PropertyType))
                            ((numberField) dataEditorControl).Enabled = false;
                    }
                    break;
                case "umbraco.editorControls.yesNo":
                    {
                        ((yesNo) dataEditorControl).Checked = Convert.ToBoolean(property.Value);
                        ((yesNo) dataEditorControl).CheckedChanged += Editor_CheckedChanged;
                        if (!_currentMemberType.MemberCanEdit(property.PropertyType))
                            ((yesNo) dataEditorControl).Enabled = false;
                    }
                    break;
                case "umbraco.editorControls.radiobox":
                    {
                        ((radiobox) dataEditorControl).SelectedValue = (string) property.Value;
                        ((radiobox) dataEditorControl).TextChanged += Editor_TextChanged;
                        if (!_currentMemberType.MemberCanEdit(property.PropertyType))
                            ((radiobox) dataEditorControl).Enabled = false;
                    }
                    break;
                case "umbraco.editorControls.datefield":
                    {
                        ((dateField) dataEditorControl).Text = (string) property.Value;
                        ((dateField) dataEditorControl).TextChanged += Editor_TextChanged;
                        if (!_currentMemberType.MemberCanEdit(property.PropertyType))
                            ((dateField) dataEditorControl).Enabled = false;
                    }
                    break;
                case "umbraco.editorControls.dropdown":
                    {
                        ((dropdown) dataEditorControl).SelectedValue = (string) property.Value;
                        ((dropdown) dataEditorControl).SelectedIndexChanged += Editor_SelectedIndexChanged;
                        if (!_currentMemberType.MemberCanEdit(property.PropertyType))
                            ((dropdown) dataEditorControl).Enabled = false;
                    }
                    break;
                case "umbraco.editorControls.simpleEditor.SimpleEditor":
                    {
                        ((SimpleEditor) dataEditorControl).Text = (string) property.Value;
                        ((SimpleEditor) dataEditorControl).TextChanged += Editor_TextChanged;
                        if (!_currentMemberType.MemberCanEdit(property.PropertyType))
                            ((SimpleEditor) dataEditorControl).Enabled = false;
                    }
                    break;
                case "umbraco.editorControls.tinymce.TinyMCE":
                case "umbraco.editorControls.tinyMCE3.TinyMCE":
                    {
                        try
                        {
                            ((TinyMCE) dataEditorControl).Text = (string) property.Value;
                            ((TinyMCE) dataEditorControl).TextChanged += Editor_TextChanged;
                        }
                        catch {}
                        if (!_currentMemberType.MemberCanEdit(property.PropertyType))
                            ((TinyMCE) dataEditorControl).Enabled = false;
                    }
                    break;
                case "umbraco.editorControls.ultimatepicker.ultimatePickerDataEditor":
                    {
                        try
                        {
                            ((ListControl) ((ultimatePickerDataEditor) dataEditorControl).Editor.Controls[0]).
                                    SelectedValue = (string) property.Value;
                            ((ListControl) ((ultimatePickerDataEditor) dataEditorControl).Editor.Controls[0]).
                                    SelectedIndexChanged += Editor_SelectedIndexChanged;
                        }
                        catch
                        {
                            // escape error
                        }
                    }
                    break;
                case "default":
                    break;
            }
            return dataEditorControl;
        }

        #endregion

        #region Event Methods

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            RegisterScripts();
            this._currentMember = Member.GetCurrentMember();
            this.BuildPropertyEditor();
        }

        /// <summary>
        /// Handles the Click event of the btnUpdate control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            e.ToString();
            this._currentMember.XmlGenerate(new XmlDocument());
            this._currentMember.Save();
        }

        /// <summary>
        /// Handles the SelectedIndexChanged event of the ProfileEditor control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Editor_SelectedIndexChanged(object sender, EventArgs e)
        {
            var alias = ((ListControl)sender).ID.Replace("editor", "");
            var value = ((ListControl)sender).SelectedItem.Value;

            this._currentMember.getProperty(alias).Value = value;
        }

        /// <summary>
        /// Handles the CheckedChanged event of the ProfileEditor control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Editor_CheckedChanged(object sender, EventArgs e)
        {
            var alias = ((CheckBox)sender).ID.Replace("editor", "");
            var value = ((CheckBox)sender).Checked;

            this._currentMember.getProperty(alias).Value = value;
        }

        /// <summary>
        /// Handles the TextChanged event of the ProfileEditor control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Editor_TextChanged(object sender, EventArgs e)
        {
            var alias = ((TextBox) sender).ID.Replace("editor", "");
            var value = ((TextBox) sender).Text;

            this._currentMember.getProperty(alias).Value = value;
        }

        #endregion
    }
}